<template>
	<view class="container">
		<Navigator2 :title="$t('device.AIvoice')"></Navigator2>
		<view class="content">
			<!-- 加载中状态 -->
			<view v-if="isLoadingData" class="loading-container">
				<view class="loading-wrapper">
					<view class="loading-spinner-large"></view>
					<text class="loading-text">{{ $t('device.loadingVoiceList') }}</text>
				</view>
			</view>
			<!-- 声音列表 -->
			<aloys-tab v-else ref="aloysTab" :tabs="tabs" @change="onTabChange" :currentTab="currentTabIndex" activeColor="#0052D9" inactiveColor="#000000" underlineColor="#0052D9">
				<template v-for="(tab, index) in tabs">
					<view :slot="`content${index}`" class="voice-content" :key="index">
						<view 
							class="voice-card" 
							:class="{ 
								'voice-selected': Number(v.id) === selectedVoiceId,
								'voice-disabled': v.isClone && v.valid === false 
							}"
							v-for="(v,i) in tab.voices" 
							:key="v.id"
							@click="selectVoice(v.id, v.name, v.isClone, v.valid)"
						>
							<view class="voice-image" v-if="v.isClone">
								<image src="/static/custom_voice.png" style="width: 64px; height: 64px;"></image>
							</view>
							<view class="voice-info">
								<view class="voice-header">
									<view class="voice-name">{{v.name}}<text v-if="v.isClone" @click="editVoice(v)">{{ $t('device.edit') }}</text></view>
								</view>
								<view class="voice-tags">
									<text class="voice-tag" v-if="v.isClone">{{ $t('device.modifiableTimes') }}:{{v.restTimes}}/10</text>
									<text class="voice-tag" v-else v-for="tag in (v.tag ? v.tag.split('、') : ['专业'])" :key="tag">{{tag}}</text>
								</view>
								<!-- 进度条 -->
								<view class="progress-container" :class="{ 'progress-visible': currentPlayingVoiceId === v.id }">
									<view class="progress-bar">
										<view class="progress-fill" :style="{width: totalDuration > 0 ? (currentProgress / totalDuration * 100) + '%' : '0%'}"></view>
									</view>
								</view>
							</view>
							<view class="play-button" @click="playVoice(v.id, v.isClone)">
								<view v-if="loadingVoiceId === v.id && isLoadingVoice" class="loading-icon">
									<view class="loading-spinner"></view>
								</view>
								<image v-else class="play-icon" :src="currentPlayingVoiceId === v.id && isPlaying ? '/static/voice_pause.png' : '/static/voice_play.png'"></image>
							</view>
						</view>
					</view>
				</template>
			</aloys-tab>
		</view>
		<view class="bottom-button">
			<button class="clone-btn" @click="clone">{{ $t('device.cloneMyVoice') }}</button>
			<button class="complete-btn" @click="onComplete">{{ $t('device.complete') }}</button>
		</view>
		<neil-modal :show="showEditVoiceModal" v-if="showEditVoiceModal" @close="closeEditVoiceModal" :title="$t('device.editVoice')" @cancel="closeEditVoiceModal"
			@confirm="saveEditVoice">
			<view class="input-view">
				<view class="input-name">
					<input type="text" v-model="editVoiceName" :placeholder="$t('device.inputVoiceName')" :placeholder-class="showEditVoiceModal ? '' : 'opacityColor'" />
					<input type="text" v-model="editVoiceDesc" :placeholder="$t('device.inputVoiceDesc')" :placeholder-class="showEditVoiceModal ? '' : 'opacityColor'" />
				</view>
				<view class="blank"></view>
				<view class="blank"></view>
			</view>
		</neil-modal>
	</view>
</template>

<script>
	import api from '@/js/api.js'
	import Navigator2 from '@/components/Navigator2.vue'
	import aloysTab from '@/components/aloys-tab/aloys-tab.vue'
	import neilModal from '@/components/neil-modal/neil-modal.vue'
	
	export default {
		data() {
			return {
				tabs: [],	// 语音列表
				id: 0,	// 设备ID
				platform: null,
				selectedVoiceId: null, // 当前选中的声音ID
				selectedVoiceName: '', // 当前选中的声音名称
				currentTabIndex: 0 ,// 当前选中的tab索引

				botId: 0,
				botName: '',
				botDesc: '',
				voiceIsClone: false,
				networkPriority: true,
				customVoiceRestTimes: 0,
				customVoiceName: '',
				customVoiceDesc: '',
				editVoiceId: 0,
				editVoiceName: '',
				editVoiceDesc: '',
				showEditVoiceModal: false,

				// 音频播放相关
				isPlaying: false,
				currentPlayingVoiceId: null,
				audioContext: null,
				currentProgress: 0,
				totalDuration: 0,
				isLoadingVoice: false,
				loadingVoiceId: null,

				// 数据加载状态
				isLoadingData: true
			}
		},
		onLoad(param) {
			console.log('页面参数:', param)
			if (param.id) {
				this.id = param.id
			}
			if (param.voiceId) {
				// 确保数据类型一致，转换为数字
				this.selectedVoiceId = Number(param.voiceId)
				console.log('初始化选中voiceId:', this.selectedVoiceId, '类型:', typeof this.selectedVoiceId)
			}
			if (param.platform) {
				this.platform = param.platform
			}
			if (param.botId) {
				this.botId = param.botId
			}
			if (param.botName) {
				 this.botName = param.botName
			}
			if (param.botDesc) {
				this.botDesc = param.botDesc
			}
			if (param.voiceIsClone) {
				this.voiceIsClone = param.voiceIsClone
			}
			if (param.networkPriority) {
				this.networkPriority = param.networkPriority
			}
		},
		mounted() {
			this.getVoices()
		},
		onUnload() {
			// 页面卸载时停止音频播放
			this.stopCurrentAudio()
		},
		methods: {
			playVoice(voiceId, isClone) {
				// 如果点击的是当前正在播放的音频，则暂停/恢复
				if (this.currentPlayingVoiceId === voiceId && this.audioContext) {
					if (this.isPlaying) {
						this.pauseAudio()
					} else {
						this.resumeAudio()
					}
					return
				}

				// 如果正在加载，则忽略点击
				if (this.isLoadingVoice && this.loadingVoiceId === voiceId) {
					return
				}

				// 停止当前播放的音频
				this.stopCurrentAudio()

				// 设置加载状态
				this.isLoadingVoice = true
				this.loadingVoiceId = voiceId

				// 获取音频URL并播放
				api.playVoice(voiceId, isClone).then(res => {
					if (res.code == 200) {
						const url = res.data
						if (!url) {
							uni.showToast({
								title: this.$t('device.playFailed'),
								icon: 'none'
							})
							this.clearLoadingState()
							return
						}
						this.playAudioFromUrl(url, voiceId)
					} else {
						this.clearLoadingState()
						uni.showToast({
							title: this.$t('device.getAudioFailed'),
							icon: 'none'
						})
					}
				}).catch(() => {
					this.clearLoadingState()
					uni.showToast({
						title: this.$t('device.networkError'),
						icon: 'none'
					})
				})
			},

			// 从URL播放音频
			playAudioFromUrl(url, voiceId) {
				this.currentPlayingVoiceId = voiceId
				this.audioContext = uni.createInnerAudioContext()
				this.audioContext.src = url

				// 音频加载完成
				this.audioContext.onCanplay(() => {
					this.totalDuration = this.audioContext.duration
				})

				// 开始播放
				this.audioContext.onPlay(() => {
					this.isPlaying = true
					this.clearLoadingState()
				})

				// 暂停播放
				this.audioContext.onPause(() => {
					this.isPlaying = false
				})

				// 播放进度更新
				this.audioContext.onTimeUpdate(() => {
					this.currentProgress = this.audioContext.currentTime
				})

				// 播放结束
				this.audioContext.onEnded(() => {
					this.isPlaying = false
					this.currentProgress = 0
					this.currentPlayingVoiceId = null
					this.clearLoadingState()
					if (this.audioContext) {
						this.audioContext.destroy()
						this.audioContext = null
					}
				})

				// 播放错误
				this.audioContext.onError((error) => {
					console.error('音频播放错误:', error)
					uni.showToast({
						title: this.$t('device.playFailed'),
						icon: 'none'
					})
					this.clearLoadingState()
					this.stopCurrentAudio()
				})

				// 开始播放
				this.audioContext.play()
			},

			// 暂停音频
			pauseAudio() {
				if (this.audioContext) {
					this.audioContext.pause()
				}
			},

			// 恢复播放
			resumeAudio() {
				if (this.audioContext) {
					this.audioContext.play()
				}
			},

			// 停止当前音频
			stopCurrentAudio() {
				if (this.audioContext) {
					this.audioContext.stop()
					this.audioContext.destroy()
					this.audioContext = null
				}
				this.isPlaying = false
				this.currentProgress = 0
				this.currentPlayingVoiceId = null
				this.clearLoadingState()
			},

			// 清除加载状态
			clearLoadingState() {
				this.isLoadingVoice = false
				this.loadingVoiceId = null
			},
			onTabChange(index) {
				console.log('Tab切换:', index)
				this.currentTabIndex = index
			},
			getVoices() {
				this.isLoadingData = true
				api.getVoices(this.platform, this.id).then(res => {
					console.log('API返回的原始数据:', res)
					console.log('当前selectedVoiceId:', this.selectedVoiceId)

					let typeArr = [...new Set(res.map(v => v.classify))]
					let tabs = []
					let found = false
					let tabIndex = 0
					let voiceIndex = 0
					for (const [i, classify] of typeArr.entries()) {
						const voices = res.filter(v => v.classify == classify)
						const tab = {title: classify, voices}
						if (classify == '我的声音') {
							this.customVoiceRestTimes = voices[0].restTimes
							this.customVoiceName = voices[0].name
							this.customVoiceDesc = voices[0].description
						}
						tabs.push(tab)
						if (!found) {
							const idx = voices.findIndex(v => Number(v.id) === this.selectedVoiceId)
							console.log(`检查tab ${i} (${classify}):`, voices.map(v => ({id: v.id, name: v.name, idType: typeof v.id})))
							if (idx !== -1) {
								tabIndex = i
								voiceIndex = idx
								found = true
								console.log(`找到匹配的voice: tabIndex=${tabIndex}, voiceIndex=${voiceIndex}`)
							}
						}
					}
					this.tabs = tabs
					this.currentTabIndex = tabIndex
					this.isLoadingData = false

					console.log('最终tabs数据:', this.tabs)
					console.log('找到选中voice:', {tabIndex, voiceIndex, selectedVoiceId: this.selectedVoiceId})

					// 延迟执行滚动，确保DOM已渲染
					this.$nextTick(() => {
						setTimeout(() => {
							this.scrollToSelectedVoice(tabIndex, voiceIndex)
						}, 500)
					})
				}).catch(err => {
					this.isLoadingData = false
					uni.showToast({
						title: this.$t('device.loadFailed'),
						icon: 'none'
					})
				})
			},
			editVoice(voice) {
				this.editVoiceId = voice.id
				this.editVoiceName = voice.name
				this.editVoiceDesc = voice.description
				this.showEditVoiceModal = true
			},
			closeEditVoiceModal() {
				this.showEditVoiceModal = false
			},
			saveEditVoice() {
				api.editVoice(this.editVoiceId, this.editVoiceName, this.editVoiceDesc).then(res => {
					if (res) {
						uni.showToast({
							title: this.$t('device.editSuccess'),
							icon: 'success'
						})
						this.closeEditVoiceModal()
						this.getVoices()
					} else {
						uni.showToast({
							title: this.$t('device.editFailed'),
							icon: 'error'
						})
					}
				})
			},
			clone() {
				const userInfo = uni.getStorageSync('userInfo')
				api.checkCloneVoiceOrder(this.id, userInfo.id).then(res => {
					if (res == 0) {
						uni.navigateTo({
							url:`/pages/device/clonevoiceorder?deviceId=${this.id}`
						})
					} else if (res == 1) {
						uni.navigateTo({
							url:`/pages/device/clonemyvoice?deviceId=${this.id}&customVoiceRestTimes=${this.customVoiceRestTimes}`
						})
					} else {
						uni.showToast({
							title: this.$t('device.pleaseOperateAfter3Minutes'),
							icon: 'none',
							duration: 3000
						})
					}
				})
			},
			onComplete() {
				// 返回上一页
				setTimeout(() => {
					uni.navigateTo({
						url:`/pages/device/devicesetting?id=${this.id}&voiceId=${this.selectedVoiceId}&voiceName=${this.selectedVoiceName}&voiceIsClone=${this.voiceIsClone}&botId=${this.botId}&botName=${this.botName}&botDesc=${this.botDesc}&networkPriority=${this.networkPriority}`
					})
				}, 500)
			},
			selectVoice(voiceId, voiceName, isClone, valid) {
				// 如果是克隆声音且valid为false，则不允许选中
				if (isClone && valid === false) {
					uni.showToast({
						title: this.$t('device.voiceUnavailable'),
						icon: 'none'
					})
					return
				}

				this.selectedVoiceId = Number(voiceId)
				this.selectedVoiceName = voiceName
				this.selectedVoiceIsClone = isClone
				console.log('选择voice:', this.selectedVoiceId)
			},
			scrollToSelectedVoice(tabIndex, voiceIndex) {
				console.log('开始滚动到voice:', {tabIndex, voiceIndex})
				
				// 延迟执行，确保swiper已经切换到正确的tab
				setTimeout(() => {
					// 使用uni.createSelectorQuery获取当前tab中的voice元素
					const query = uni.createSelectorQuery().in(this)
					query.selectAll('.voice').boundingClientRect(rects => {
						if (rects && rects.length > 0) {
							console.log('找到voice元素数量:', rects.length)
							
							// 计算目标voice在当前tab中的索引
							let targetIndex = 0
							for (let i = 0; i < tabIndex; i++) {
								targetIndex += this.tabs[i].voices.length
							}
							targetIndex += voiceIndex
							
							console.log('目标voice索引:', targetIndex)
							
							if (rects[targetIndex]) {
								const targetRect = rects[targetIndex]
								console.log('目标voice位置:', targetRect)
								
								// 尝试调用aloys-tab的滚动方法
								if (this.$refs.aloysTab) {
									this.$refs.aloysTab.scrollToPosition(targetRect.top - 100)
								}
							}
						}
					}).exec()
				}, 800) // 增加延迟时间，确保tab切换完成
			}
		},
		components: {
			Navigator2,
			aloysTab,
			neilModal
		}
	}
</script>

<style lang="scss" scoped>
	.container {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		background: linear-gradient(180deg, #f8fafc 0%, #f1f5f9 100%);
	}
	
	.content {
		height: calc(100% - 88rpx - 80rpx);
		padding-bottom: 150rpx; /* 为底部按钮留出空间 */
		box-sizing: border-box;
	}
	
	.voice-content {
		padding: 30rpx 30rpx 40rpx 30rpx;
	}
	
	.voice-card {
		background: #FFFFFF;
		border-radius: 16rpx;
		border: 2rpx solid transparent;
		padding: 32rpx;
		margin-bottom: 30rpx;
		box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.05);
		transition: all 0.3s ease;
		cursor: pointer;
		display: flex;
		align-items: center;
		justify-content: space-between;
		
		&.voice-selected {
			border: 2rpx solid #667eea;
			box-shadow: 0 8rpx 32rpx rgba(102, 126, 234, 0.3);
		}
		
		.voice-image {
			margin-right: 12px;
		}

		.voice-info {
			flex: 1;
			margin-right: 24rpx;
		}
		
		.voice-header {
			margin-bottom: 16rpx;
		}
		
		.voice-name {
			font-size: 28rpx;
			font-weight: 600;
			color: #1F2937;
			margin-bottom: 8rpx;
			line-height: 1.3;
			text {
				font-weight: normal;
				margin-left: 6px;
				color: #7A68F7;
			}
		}
		
		.voice-tags {
			display: flex;
			flex-wrap: wrap;
			gap: 12rpx;
		}
		
		.voice-tag {
			font-size: 24rpx;
			color: #348013;
			background: #F2FAED;
			padding: 8rpx 16rpx;
			border-radius: 50rpx;
			display: inline-block;
		}

		// 进度条样式
		.progress-container {
			margin-top: 16rpx;
			height: 24rpx; /* 固定高度，包含进度条和间距 */
			opacity: 0;
			visibility: hidden;
			transition: opacity 0.3s ease, visibility 0.3s ease;

			&.progress-visible {
				opacity: 1;
				visibility: visible;
			}
		}

		.progress-bar {
			width: 100%;
			height: 8rpx;
			background: #EBEFF5;
			border-radius: 8rpx;
			overflow: hidden;
		}

		.progress-fill {
			height: 100%;
			background: #59B22D;
			border-radius: 8rpx;
			transition: width 0.3s ease;
		}
		
		.play-button {
			width: 80rpx;
			height: 80rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}
		
		.play-icon {
			width: 49rpx;
			height: 49rpx;
			padding: 8rpx;
		}

		.loading-icon {
			width: 49rpx;
			height: 49rpx;
			display: flex;
			align-items: center;
			justify-content: center;
		}

		.loading-spinner {
			width: 32rpx;
			height: 32rpx;
			border: 4rpx solid #E5E5E5;
			border-top: 4rpx solid #0052D9;
			border-radius: 50%;
			animation: spin 1s linear infinite;
		}
	}

	@keyframes spin {
		0% {
			transform: rotate(0deg);
		}
		100% {
			transform: rotate(360deg);
		}
	}

	// 加载状态样式
	.loading-container {
		height: calc(100vh - 88rpx - 80rpx - 150rpx);
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.loading-wrapper {
		display: flex;
		flex-direction: column;
		align-items: center;
		gap: 24rpx;
	}

	.loading-spinner-large {
		width: 64rpx;
		height: 64rpx;
		border: 6rpx solid #E5E5E5;
		border-top: 6rpx solid #0052D9;
		border-radius: 50%;
		animation: spin 1s linear infinite;
	}

	.loading-text {
		font-size: 28rpx;
		color: #999;
	}

	.input-name {
		overflow: hidden;
		input {
			padding-left: 10px;
			border: solid 1px #CCCCCC;
			margin: 20px 20px;
			font-size: 18px;
			height: 40px;
			line-height: 40px;
			border-radius: 8px;
		}
	}
	
	.bottom-button {
		display: flex;
		position: absolute;
		bottom: 0;
		left: 0;
		width: 100%;
		padding: 20rpx;
		background-color: #FFFFFF;
		box-sizing: border-box;
		
		.clone-btn {
			width: 48%;
			background-color: #F5F5F5;
			height: 100rpx;
			border-radius: 8px;
			font-size: 32rpx;
			border: none !important;
			color: #000000;
			display: flex;
			justify-content: center;
			align-items: center;
			outline: none;
			padding: 7px 15px;
			&::after {
				border: none;
			}

			&:active {
				background-color: #E8E5FF;
			}
		}
		.complete-btn {
			width: 48%;
			height: 100rpx;
			background-color: #0256FF;
			border-radius: 8px;
			font-size: 32rpx;
			font-weight: 500;
			color: #FFFFFF;
			border: none;
			padding: 7px 15px;

			display: flex;
			justify-content: center;
			align-items: center;
			
			&:active {
				background-color: #0052D9;
			}
		}
	}
	
	// 覆盖tab样式
	// ::v-deep .tab-item {
	// 	font-weight: 500;
	// 	color: #64748b;
	// 	transition: all 0.3s ease;
		
	// 	&.active {
	// 		border-bottom: 4rpx solid #667eea !important;
	// 		color: #667eea !important;
	// 		font-weight: 600;
	// 	}
	// }
	// Tab栏样式优化
	::v-deep .tabs {
		border-bottom: 2rpx solid #F0F0F0;
		padding: 0 16rpx;
	}

	::v-deep .tab-item {
		font-size: 32rpx;
		color: #BFBFBF;
		font-weight: 400;
		min-width: 140rpx;
		padding: 0 32rpx !important;
	}

	::v-deep .tab-item.active {
		font-size: 32rpx !important;
		font-weight: 600 !important;
		color: #0052D9 !important;
		border-bottom: 4rpx solid #0052D9 !important;
	}

	.opacityColor{
		color: transparent !important;
	}
	.neil-modal__content {
		padding-bottom: 1px !important;
	}
</style>
<style>
	.opacityColor{
		color: transparent !important;
	}
</style>